package com.tengxing.e1.FactoryTest;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.maiarstar.e101.protocol.cerebellum.api.exception.ProtocolException;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolGetter;
import com.maiarstar.e101.protocol.cerebellum.sdk.CerebellumProtocolSdkManager;

public class IMU_Test_Activity extends AppCompatActivity {
    private static final String TAG = "IMU_Test_Activity";
    private CerebellumProtocolSdkManager cerebellumProtocolSdkManager;
    TextView tV_IMU_Val1, tV_IMU_Val2, tV_IMU_Val3;
    Button btn_IMU_Pass, btn_IMU_Fail, btn_IMU_Get;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    double x, y, z;
    private static Handler handler_refresh_status_task;
    private static Runnable run_refresh_status_task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_imu_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        initCerebellumManager();
        tV_IMU_Val1 = findViewById(R.id.tV_IMU_Val1);
        tV_IMU_Val2 = findViewById(R.id.tV_IMU_Val2);
        tV_IMU_Val3 = findViewById(R.id.tV_IMU_Val3);
        Factory_IMU_BTN();
        Refresh_Status_Task_Init();
    }

    private void initCerebellumManager() {
        CerebellumProtocolSdkManager sdkProtocolManager = new CerebellumProtocolSdkManager(this);
        CerebellumProtocolSdkManager.SdkParams sdkParams = CerebellumProtocolSdkManager.getDeafultSdkParams();
        try {
            sdkProtocolManager.init(sdkParams);
        } catch (ProtocolException e) {
            Log.w(TAG, e.getMessage());
        }
        this.cerebellumProtocolSdkManager = sdkProtocolManager;
    }


    private void Factory_IMU_BTN(){
        btn_IMU_Pass = findViewById(R.id.btn_IMU_Pass);
        btn_IMU_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("IMU","通过");
                if(editor.commit()){
                    Toast.makeText(IMU_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(IMU_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(IMU_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_IMU_Fail = findViewById(R.id.btn_IMU_Fail);
        btn_IMU_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("IMU","未通过");
                if(editor.commit()){
                    Toast.makeText(IMU_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(IMU_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(IMU_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }
    private void Refresh_Status_Task_Init(){
        handler_refresh_status_task = new Handler(Looper.getMainLooper());//新建任务
        run_refresh_status_task = new Runnable() {
            @Override
            public void run() {
                handler_refresh_status_task.postDelayed(this, 2000);
                boolean gyro_flag = false, accel_flag = false, mag_flag = false;
                String str_status = "传感器";
                if(Refresh_IMU_Status(1, tV_IMU_Val1)){
                    gyro_flag = true;
                }
                if(Refresh_IMU_Status(2, tV_IMU_Val2)){
                    accel_flag = true;
                }
                if(Refresh_IMU_Status(3, tV_IMU_Val3)){
                    mag_flag = true;
                }

                if(gyro_flag && accel_flag && mag_flag){
                    //Toast.makeText(IMU_Test_Activity.this, "所有刷新成功", Toast.LENGTH_SHORT).show();
                }else{
                    if(!gyro_flag){
                        str_status = str_status.concat("角速度 ");
                    }
                    if(!gyro_flag){
                        str_status = str_status.concat("加速度 ");
                    }
                    if(!gyro_flag){
                        str_status = str_status.concat("磁场 ");
                    }
                    Toast.makeText(IMU_Test_Activity.this, str_status+"刷新失败", Toast.LENGTH_SHORT).show();
                }
                //Log.d(TAG, "Refresh_Status_Cycle:in");
            }
        };
        handler_refresh_status_task.post(run_refresh_status_task);//启动任务
        //Log.d(TAG, "Refresh_Status_Cycle:out");
    }
    private boolean Refresh_IMU_Status(int num, TextView tV){
        if(GetIMU(num)){
            String imu_str = x + ", "+ y + ", " + z;
            tV.setText(imu_str);
            return true;
        }else{
            tV.setText("获取失败");
            return false;
        }
    }
    private boolean GetIMU(int num) throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            //getter.getIMUInfo(num);
            x = getter.getIMUInfo(num).getX();
            y = getter.getIMUInfo(num).getY();
            z = getter.getIMUInfo(num).getZ();
            return true;
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(IMU_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
        finish();
        Toast.makeText(IMU_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }
}